package CreationPattern.Prototype;

import lombok.SneakyThrows;

import java.io.*;

/**
 * @Classname : SerialCopySheep
 * @Description : 深拷贝 —— 序列化实现
 * @Author : chentianyu
 * @Date 2023/1/23 22:26
 */


public class SerialCopySheep extends Sheep implements Serializable {

    private static final long serialVersionUID = 5056393381304053680L;

    /**
     * 序列化数组
     */
    private byte[] bytes;

    public SerialCopySheep() {
        super();
    }
    public SerialCopySheep(String name) {
        super(name);
        this.bytes = this.getBytes();
    }

    /**
     * 获取序列化数组
     *
     * @return
     */
    @SneakyThrows
    private byte[] getBytes() {
        ByteArrayOutputStream bas = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bas);
        oos.writeObject(this);
        return bas.toByteArray();
    }

    @SneakyThrows
    @Override
    public SerialCopySheep clone() {
        ByteArrayInputStream bis = new ByteArrayInputStream(this.bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (SerialCopySheep) ois.readObject();
    }
}
